// 获取URL中的新闻ID和类型
function getUrlParams() {
    const params = new URLSearchParams(window.location.search);
    return {
        mid: parseInt(params.get('mid')),
        type: parseInt(params.get('type'))
    };
}

// 检查用户是否点赞过该新闻
async function checkUserLikeStatus(mid) {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    try {
        const response = await API.comment.vote({
            mid: mid,
            uid: userInfo.uid
        });
        if (response.votesum && Array.isArray(response.votesum)) {
            // 计算该用户的所有upvote总和
            const totalUpvotes = response.votesum.reduce((sum, item) => sum + (item.upvote || 0), 0);
            return totalUpvotes === 1; // 总和为1表示已点赞，否则表示未点赞
        }
        return false; // 默认返回未点赞
    } catch (error) {
        console.error('检查点赞状态失败:', error);
        return false;
    }
}

// 获取新闻的总点赞数
async function getNewsLikesCount(mid) {
    try {
        const response = await API.comment.vote({
            mid: mid,
        });
        if (response.votesum && Array.isArray(response.votesum)) {
            // 计算所有upvote总和
            const totalLikes = response.votesum.reduce((sum, item) => sum + (item.upvote || 0), 0);
            return totalLikes;
        }
        return 0; // 默认返回0
    } catch (error) {
        console.error('获取点赞数失败:', error);
        return 0;
    }
}

// 加载新闻详情
async function loadNewsDetail() {
    const { mid } = getUrlParams();
    if (!mid) {
        window.location.href = 'index.html';
        return;
    }

    try {
        const response = await API.message.getDetail({
            mid: mid
        });

        // 获取点赞状态和点赞数
        const isLiked = await checkUserLikeStatus(mid);
        const likesCount = await getNewsLikesCount(mid);

        const { messages, photo } = response;
        const newsDetail = document.getElementById('newsDetail');

        let contentHtml = `
            <h1 class="news-title">${messages.head}</h1>
            <div class="news-meta">
                <div class="date-container">
                    <i class="far fa-calendar-alt"></i>
                    <span>${new Date(messages.mtime).toLocaleDateString('zh-CN')}</span>
                </div>
                <div class="like-container">
                    <button class="like-btn ${isLiked ? 'liked' : ''}" onclick="handleLike(${messages.mid})">
                        <i class="like-icon ${isLiked ? 'fas' : 'far'} fa-heart"></i>
                        <span class="like-count">${likesCount} 赞</span>
                    </button>
                </div>
            </div>
            <div class="news-content">${messages.context}</div>
        `;

        if (photo && photo.length > 0) {
            contentHtml += `
                <div class="news-images">
                    ${photo.map(p => {
                        const imageUrl = FileUtils.decodeToUrl(p.photodata);
                        return `
                            <img src="${imageUrl}" 
                                 alt="新闻图片" 
                                 class="news-image"
                                 onclick="showFullImage('${imageUrl}')">
                        `;
                    }).join('')}
                </div>
            `;
        }

        newsDetail.innerHTML = contentHtml;

        // 加载评论区
        loadComments(mid);
        showCommentForm();

    } catch (error) {
        console.error('加载新闻详情失败:', error);
        alert('加载新闻详情失败');
    }
}

// 加载评论列表
async function loadComments(mid) {
    try {
        const response = await API.comment.find({
            mid: mid
        });

        const commentsList = document.getElementById('commentsList');
        
        if (Array.isArray(response)) {
            // 过滤掉评论内容为空的评论
            const validComments = response.filter(comment => comment.commnet && comment.commnet.trim() !== '');
            
            commentsList.innerHTML = validComments.map(comment => `
                <div class="comment-item">
                    <div class="comment-meta">
                        <span>${comment.uid}</span>
                    </div>
                    <div class="comment-content">${comment.commnet}</div>
                </div>
            `).join('');
        }
    } catch (error) {
        console.error('加载评论失败:', error);
    }
}

// 显示评论表单
function showCommentForm() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const commentForm = document.getElementById('commentForm');
    
    if (userInfo && userInfo.uid) {
        commentForm.innerHTML = `
            <textarea id="commentText" placeholder="写下你的评论..."></textarea>
            <button onclick="submitComment()">发表评论</button>
        `;
    } else {
        commentForm.innerHTML = `
            <p>请先 <a href="../login.html">登录</a> 后发表评论</p>
        `;
    }
}

// 提交评论
async function submitComment() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo) return;

    const commentText = document.getElementById('commentText').value;
    const { mid } = getUrlParams();

    if (!commentText.trim()) {
        alert('请输入评论内容');
        return;
    }

    try {
        await API.comment.add({
            commnet: commentText,
            uid: userInfo.uid,
            mid: mid,
            upvote: 0
        });

        loadComments(mid);
        document.getElementById('commentText').value = '';
    } catch (error) {
        alert('发表评论失败');
        console.error('发表评论失败:', error);
    }
}

// 图片全屏预览
function showFullImage(imageUrl) {
    const overlay = document.createElement('div');
    overlay.className = 'image-overlay';
    overlay.onclick = () => {
        document.body.removeChild(overlay);
    };

    const img = document.createElement('img');
    img.src = imageUrl;
    overlay.appendChild(img);
    document.body.appendChild(overlay);
}

// 处理点赞事件
async function handleLike(mid) {
    try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
            alert('请先登录后再点赞');
            return;
        }

        // 获取当前点赞状态
        const likeBtn = document.querySelector('.like-btn');
        const isCurrentlyLiked = likeBtn.classList.contains('liked');

        // 根据当前状态设置upvote值
        await API.comment.add({
            uid: userInfo.uid,
            mid: mid,
            upvote: isCurrentlyLiked ? -1 : 1  // 如果当前已点赞则设为-1，否则设为1
        });

        // 更新UI
        const likeIcon = likeBtn.querySelector('.like-icon');
        const likeCount = likeBtn.querySelector('.like-count');
        
        // 切换点赞状态
        likeBtn.classList.toggle('liked');
        likeIcon.classList.toggle('fas');
        likeIcon.classList.toggle('far');
        
        // 更新点赞数
        const currentCount = parseInt(likeCount.textContent);
        likeCount.textContent = `${currentCount + (isCurrentlyLiked ? -1 : 1)} 赞`;
        
    } catch (error) {
        console.error('点赞失败:', error);
        alert('点赞失败，请稍后重试');
    }
}

// 页面加载完成后执行初始化
document.addEventListener('DOMContentLoaded', () => {
    loadNewsDetail();
});